package com.c2b.algorithm.leetcode.base.unionfind;

/**
 * @author c2b
 * @since 2024/3/5 11:34
 */
public class LC695 {
    static class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int maxArea = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (grid[i][j] == 1) {
                        maxArea = Math.max(maxArea, dfs(i, j, grid));
                    }
                }
            }
            return maxArea;
        }

        private int dfs(int row, int col, int[][] grid) {
            // 如果越界 或者 当前位置不再是岛屿，return
            if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length || grid[row][col] == 0) {
                return 0;
            }
            grid[row][col] = 0;
            int num = 1;
            int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
            for (int[] direction : directions) {
                num += dfs(row + direction[0], col + direction[1], grid);
            }
            return num;
        }
    }
}
